package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TradeProvinceOrderWindow;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.function.DimAsyncFunction;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/12/14 13:47
 */
public class Dws_10_DwsTradeProvinceOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_10_DwsTradeProvinceOrderWindow().init(
            4010,
            2,
            "Dws_10_DwsTradeProvinceOrderWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream = parseToPojo(stream);
        
        beanStream = distinctByOrderDetailId(beanStream);
        
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStreamWithOutDim
            = windowAndAgg(beanStream);
    
        SingleOutputStreamOperator<TradeProvinceOrderWindow> resultStream = joinDim(beanStreamWithOutDim);
    
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_province_order_window", TradeProvinceOrderWindow.class));
    
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> joinDim(SingleOutputStreamOperator<TradeProvinceOrderWindow> stream) {
      return  AsyncDataStream.unorderedWait(
            stream,
            new DimAsyncFunction<TradeProvinceOrderWindow>() {
                @Override
                public String getTable() {
                    return "dim_base_province";
                }
    
                @Override
                public String getId(TradeProvinceOrderWindow input) {
                    return input.getProvinceId();
                }
    
                @Override
                public void addDim(TradeProvinceOrderWindow input,
                                   JSONObject dim) {
                    input.setProvinceName(dim.getString("NAME"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> windowAndAgg(
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeProvinceOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(TradeProvinceOrderWindow::getProvinceId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeProvinceOrderWindow>() {
                    @Override
                    public TradeProvinceOrderWindow reduce(TradeProvinceOrderWindow value1,
                                                           TradeProvinceOrderWindow value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.getOrderIdSet().addAll(value2.getOrderIdSet()); // 把 v2的 set 集合的所有元素, 放入到 v1 中
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeProvinceOrderWindow, TradeProvinceOrderWindow, String, TimeWindow>() {
                    @Override
                    public void process(String s,
                                        Context ctx,
                                        Iterable<TradeProvinceOrderWindow> elements,
                                        Collector<TradeProvinceOrderWindow> out) throws Exception {
                        TradeProvinceOrderWindow bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
                        
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
    
                        bean.setTs(System.currentTimeMillis());
    
                        out.collect(bean);
    
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> distinctByOrderDetailId(
        SingleOutputStreamOperator<TradeProvinceOrderWindow> beanStream) {
        return beanStream
            .keyBy(TradeProvinceOrderWindow::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeProvinceOrderWindow, TradeProvinceOrderWindow>() {
                
                private ValueState<TradeProvinceOrderWindow> lastBeanState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastBeanState = getRuntimeContext().getState(new ValueStateDescriptor<TradeProvinceOrderWindow>("lastBeanState", TradeProvinceOrderWindow.class));
                }
                
                @Override
                public void processElement(TradeProvinceOrderWindow bean,
                                           Context ctx,
                                           Collector<TradeProvinceOrderWindow> out) throws Exception {
                    TradeProvinceOrderWindow lastBean = lastBeanState.value();
                    
                    if (lastBean == null) {  // 同一个详情id 的第一条数据过来, 直接输出
                        out.collect(bean);
                        // 存入到状态中
                        lastBeanState.update(bean);
                    } else {
                        
                        TradeProvinceOrderWindow newBean = new TradeProvinceOrderWindow();
                        BeanUtils.copyProperties(newBean, bean);  // 把 bean 中所有属性的值复制到 newBean 中
                        lastBeanState.update(newBean);  // 更新修改前的数据
                        
                        // 第二条数据进来. bean如果直接修改,
                        bean.setOrderAmount(bean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        out.collect(bean);
                    }
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrderWindow> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradeProvinceOrderWindow>() {
                @Override
                public TradeProvinceOrderWindow map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    
                    return TradeProvinceOrderWindow.builder()
                        .provinceId(obj.getString("province_id"))
                        .orderDetailId(obj.getString("id"))
                        .orderIdSet(new HashSet<>(Collections.singletonList(obj.getString("order_id"))))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
                }
            });
        
    }
}
/*
从 Kafka 读取业务数据，筛选订单表数据，统计各省份各窗口订单数和订单金额

数据源:
    下单事务事实表
    
按照详情 id 去重
    要

开窗聚合
    订单金额 直接聚和相加
    
    订单数  count(*)
    
订单数方法1:
    详情1   订单1    金额100   订单数1
    详情2   订单1    金额200   订单数0
    ....
    
订单数方法 2:
    set 集合, 存储订单 id
    
    等到聚会完成之后,把 set 集合长度就是订单数
    
 
 补充维度
 
 写出 clickhouse


 */